import 'dart:async';
import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class MessagePage extends StatefulWidget {
  @override
  _MessagePageState createState() => _MessagePageState();
}

class _MessagePageState extends State<MessagePage> {
  var content = [];
  WebSocket _webSocket;

  //初始化websocket
  initWebSocket() async {
    // ignore: close_sinks
    _webSocket =
        await WebSocket.connect("ws://192.168.108.205:8080/websocket/user001");
    //监听函数
    _webSocket.listen(_onReceive, onDone: () {
      print('连接关闭时响应');
    }, onError: (error) {
      print('发生错误');
    }, cancelOnError: true);
    _webSocket.add("客户端发送过去的");
  }

  //接受数据
  void _onReceive(data) {
    if (data.runtimeType == String) {
      print("String received");
      String dataString = data;
      print(dataString.length);
      print(dataString);
      DateTime dateTime = DateTime.now();
      var msg = {
        "title": dataString,
        "subtitle": dataString,
        "date": dateTime.toString(),
      };
      content.add(msg);

      setState(() {});
    } else if (data.runtimeType.toString() == "_Uint8ArrayView") {
      Uint8List binaryIntList = data;
      //这里开始处理二进制数据了
    }
  }

  @override
  Future<void> initState() {
    // TODO: implement initState
    initWebSocket();

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: ListView.separated(
        itemCount: content.length,
        itemBuilder: (context, index) {
          print(content);
          return ListTile(
            leading: Icon(Icons.adb_outlined),
            title: Text(content[index]['title']),
            subtitle: Text(content[index]['subtitle']),
            trailing: Text(content[index]['date']),
          );
        },
        separatorBuilder: (context, index) {
          return Divider();
        },
      ),
    );
  }
}
